#include "AsioIOContextPool.h"
#include <iostream>

AsioIOContextPool::AsioIOContextPool(size_t size):_io_contexts(size),_io_index(0){
	for (int i = 0; i < size; ++i) {
		_work_guards.emplace_back(boost::asio::make_work_guard(_io_contexts[i]));
		_threads.emplace_back([this, i]() {
			_io_contexts[i].run();
			});
	}
}
AsioIOContextPool::~AsioIOContextPool() {

}
void AsioIOContextPool::Stop()
{
	for (int i = 0; i < _io_contexts.size(); ++i) {
		_work_guards[i].reset();
		_io_contexts[i].stop();
		_threads[i].join();
	}
}
AsioIOContextPool& AsioIOContextPool::GetInstance()
{
	static AsioIOContextPool instance;
	return instance;
}

boost::asio::io_context& AsioIOContextPool::GetIOContext()
{
	if (_io_index == _io_contexts.size()) {
		_io_index = 0;
	}
	return _io_contexts[_io_index++];
}
